﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace PocketMahjong.Core
{
	public class Layout
	{
		#region Properties

		public List<Position> Positions
		{
			get;
			private set;
		}

		public string Name
		{
			get;
			set;
		}

		public int LayerCount
		{
			get;
			private set;
		}

		public int RowCount
		{
			get;
			private set;
		}

		public int ColumnCount
		{
			get;
			private set;
		}

		public Layout()
		{
			Positions = new List<Position>();
		}

		#endregion

		/*public static Layout Import(Stream data)
		{
			var res = new Layout();
			StreamReader sr = new StreamReader(data);
			while (!sr.EndOfStream)
			{
				var str = sr.ReadLine();
				if (str.StartsWith("#"))
				{
					if (string.IsNullOrEmpty(res.Description))
						res.Description = str.TrimStart('#').Trim();
				}
				else
				{
					var match = Regex.Match(str, @"(\d+?)\s+?(\d+?)\s+?(\d+?)");
					if (match.Success)
					{
						var pos = new Position(int.Parse(match.Groups[3].Value), 
							int.Parse(match.Groups[1].Value),
							int.Parse(match.Groups[2].Value));
						res.LayerCount = Math.Max(res.LayerCount, pos.Layer + 1);
						res.RowCount = Math.Max(res.RowCount, pos.Row + 1);
						res.ColumnCount = Math.Max(res.ColumnCount, pos.Column + 1);
						res.Positions.Add(pos);
					}
				}
			}
			return res;
		}*/

		public static Layout Load(Stream stream)
		{
			Layout res = new Layout();
			int count = stream.ReadByte();
			res.Positions = new List<Position>(count);
			for (int i = 0; i < count; i++)
			{
				var pos = Position.Read(stream);
				res.Positions.Add(pos);
				res.LayerCount = Math.Max(res.LayerCount, pos.Layer + 1);
				res.RowCount = Math.Max(res.RowCount, pos.Row + 1);
				res.ColumnCount = Math.Max(res.ColumnCount, pos.Column + 1);
			}
			return res;
		}

		public void Save(Stream stream)
		{
			stream.WriteByte((byte)Positions.Count);
			foreach (var pos in Positions)
				pos.Write(stream);
		}
	}
}
